from rest_framework import serializers
import logging, requests, pymysql, datetime, json, xlrd, math
from django_redis import get_redis_connection
from decimal import Decimal
from django.conf import settings

from equity_admin.filters_orders import *
from businesses.utils import cancel_group_order
from equity_mall.utils.utils import redis_scheme_token_wyh
from equity_mall.utils.qiniu_storage import pic_upload
from orders.utils import schengle
from merchants.models import *
from users.models import *
from activities.models import *
from goods.models import *
from postallive.models import *
from equity_mall.utils.express_utils import KuaiDi100

logger = logging.getLogger('django')


class OrderGoodsModelSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    goods_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ['id', 'count', 'point', 'merchant', 'default_image', 'goods_name', 'price', 'level_name', 'goods_id']

    def get_level_name(self, obj):
        try:
            if obj.launched_goods:
                return obj.launched_goods.level.name
            else:
                return ''
        except:
            return ''

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except:
            return ''

    def get_goods_name(self, obj):
        try:
            return obj.goods.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        try:
            merchant = obj.merchant
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
        except:
            pass
        return data


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    customer_user_mobile = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_point', 'use_time', 'total_price', 'level_name',
                  'customer_user_mobile', 'orderNum', 'order_species', 'order_species_str', 'freight', 'payment_time']

    def get_customer_user_mobile(self, obj):
        try:
            return obj.customer_user.mobile
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return f'{obj.level.name}(分店)'
        except:
            return '总店'


class OrderFundTransModelSerializer(serializers.ModelSerializer):

    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'trans_date', 'exchange_amount', 'status', 'status_str', 'identity', 'name', 'pay_fund_order_id', 'sub_msg']


class AfterSaleApplicationFormModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg',
                  'refund_time', 'reason', 'img_array', 'application_num']

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data


class RefundOrderInfoModelSerializer(serializers.ModelSerializer):

    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    user = serializers.SerializerMethodField(read_only=True)
    refund_status_str = serializers.CharField(source='get_refund_status_display', read_only=True)
    refund_type_str = serializers.CharField(source='get_refund_type_display', read_only=True)
    operator_role_str = serializers.CharField(source='get_operator_role_display', read_only=True)

    class Meta:
        model = RefundOrderInfo
        fields = ['id', 'refund_time', 'user', 'refund_order_id', 'refund_transaction_id', 'refund_money', 'refund_procedure_money', 'refund_status',
                  'refund_status_str', 'return_msg', 'refund_type', 'refund_type_str', 'operator_role', 'operator_role_str', 'remark']

    def get_user(self, obj):
        try:
            user = obj.user
            return user.nickname
        except Exception as e:
            return ''


class OrderAddressModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsModelSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    companyuser = serializers.SerializerMethodField(read_only=True)
    orderfundtrans_set = OrderFundTransModelSerializer(many=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    bill = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    refundorderinfo_set = serializers.SerializerMethodField(read_only=True)
    after_sale = serializers.SerializerMethodField(read_only=True)
    group_data = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state_str', 'ordergoods_set', 'total_point', 'customer_user', 'companyuser',
                  'total_price', 'realpay_amount', 'discount_amount', 'orderfundtrans_set', 'state', 'use_time', 'orderNum', 'order_species', 'order_species_str',
                  'bill', 'express_info', 'orderaddress', 'refund_money', 'refundorderinfo_set', 'after_sale', 'freight', 'order_type', "order_type_str",
                  'group_data', 'payment_time']

    def get_after_sale(self, obj):
        try:
            after_sale = AfterSaleApplicationForm.objects.exclude(form_status=4).filter(order_id=obj.id).last()
            if after_sale:
                return AfterSaleApplicationFormModelSerializer(after_sale).data
            else:
                return {}
        except:
            return {}

    def get_group_data(self, obj):
        data = {}
        if obj.state in [13]:
            return data
        data['group_status'] = ''
        data['expired_time'] = ''
        data['account'] = ''
        data['people_list'] = []
        data['count'] = ''
        data['qrcode'] = ''
        data['share_pic'] = ''
        data['goods'] = {}
        data['is_self'] = 0
        try:
            group = obj.group
            if group:
                if group.group_status == 1:
                    cancel_group_order(group)
                if obj.state == 8:
                    data['group_status'] = 3
                else:
                    data['group_status'] = group.group_status if group.group_status != 0 else 4
                data['expired_time'] = group.expired_time.strftime("%Y-%m-%d %H:%M:%S")
                data['account'] = group.account
                goods = group.goods
                data['goods'] = {
                    "id": goods.id,
                    "price": goods.price,
                    "default_image": goods.default_image.url,
                    "name": goods.name,
                    "group_price": goods.group_price,
                }
                order_set = OrderInfo.objects.filter(group_id=obj.group_id, state__in=[15, 2, 8, 1, 3])
                count = group.group_order_num - len(order_set)
                data['count'] = count
                for order in order_set:
                    customeruservice = order.customeruservice
                    if customeruservice.avatar:
                        data['people_list'].append(customeruservice.avatar)
                    else:
                        data['people_list'].append('https://suppliera.postwork.cn/static/img/header.f38b3311.png')
                for i in range(count):
                    data['people_list'].append('https://jinjian.sutpay.cn/image/wyh_img128.png')
                if not group.qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/pro_detail_group/pro_detail_group",
                        "scene": f"id={goods.id}&account={group.account}",
                        "is_hyaline": True,
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    market_code = pic_upload(reslut)
                    # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                    # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                    group.qrcode = market_code
                    group.save()
                    data['qrcode'] = f'https://circle.sutpay.cn/{market_code}'
                else:
                    data['qrcode'] = group.qrcode.url
                data['share_pic'] = group.share_pic.url
        except:
            pass
        return data

    def get_refundorderinfo_set(self, obj):
        try:
            refundorderinfo_set = obj.refundorderinfo_set.all()
            return RefundOrderInfoModelSerializer(refundorderinfo_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount - obj.total_point/100).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount - obj.total_point/100).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['level'] = ''
        data['mobile'] = ''
        data['id'] = ''
        data['merchant'] = []
        data['is_merchant'] = 0
        try:
            customer_user = obj.customer_user
            level = customer_user.level
            data['id'] = customer_user.id
            data['realname'] = customer_user.realname
            data['mobile'] = customer_user.mobile
            merchant_set = Merchant.objects.filter(managermobile=customer_user.mobile)
            if level:
                data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            if merchant_set:
                data['is_merchant'] = 1
                merchant_list = []
                for merchant in merchant_set:
                    level = merchant.level
                    merchant_data = {}
                    merchant_data['id'] = merchant.id
                    merchant_data['business_no'] = merchant.wyfMerchantID
                    merchant_data['short_name'] = merchant.short_name
                    merchant_data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
                    merchant_list.append(merchant_data)
                data['merchant'] = merchant_list
            return data
        except Exception as e:
            pass
        return data

    def get_companyuser(self, obj):
        data = {}
        data['nickname'] = ''
        data['level'] = ''
        data['success_time'] = ''
        try:
            goodscoupons = obj.goodscoupons_set.all().order_by('-use_time').first()
            data['success_time'] = goodscoupons.use_time.strftime("%Y-%m-%d %H:%M:%S")
            companyuser = goodscoupons.use_user
            level = companyuser.level
            data['nickname'] = f'{companyuser.nickname}({companyuser.mobile})'
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            return data
        except:
            pass
        return data

    def get_bill(self, obj):
        data = {}
        data['id'] = ''
        data['receipts_time'] = ''
        data['bill_state'] = ''
        data['bill_state_str'] = ''
        data['settlement_time'] = ''
        data['settlement_record_id'] = ''
        try:
            bill = obj.bill
            data['id'] = bill.id
            data['receipts_time'] = bill.receipts_time.strftime("%Y-%m-%d")
            data['bill_state'] = bill.bill_state
            data['bill_state_str'] = bill.get_bill_state_display()
            data['settlement_time'] = bill.settlement_time.strftime("%Y-%m-%d")
            data['settlement_record_id'] = bill.settlement_record_id
        except:
            pass
        return data


class OrderInfoGROUPListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    group_status_str = serializers.CharField(source='get_group_status_display', read_only=True)
    order_num = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfoGROUP
        fields = ['id', 'create_time', 'group_status', 'group_status_str', 'expired_time', 'group_order_num', 'order', 'order_num']

    def get_order(self, obj):
        data = {}
        data['goods_id'] = ''
        data['goods_name'] = ''
        data['merchant_name'] = ''
        data['merchant_id'] = ''
        data['level_name'] = ''
        data['order_id'] = ''
        data['id'] = ''
        data['default_image'] = ''
        data['price'] = ''
        data['group_price'] = ''
        try:
            order = OrderInfo.objects.get(id=obj.order_id)
            goods = obj.goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['merchant_name'] = goods.merchant.name
            data['merchant_id'] = goods.merchant_id
            if order.level:
                data['level_name'] = f'{order.level.name}(分店)'
            else:
                data['level_name'] = '总店'
            data['order_id'] = order.order_id
            data['id'] = order.id
            data['default_image'] = goods.default_image.url
            data['price'] = goods.price
            data['group_price'] = goods.group_price
        except:
            pass
        return data

    def get_order_num(self, obj):
        order_num =  OrderInfo.objects.filter(state__in=[2,3,15,8], group_id=obj.id).count()
        return order_num


class OrderInfoGROUPRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    group_status_str = serializers.CharField(source='get_group_status_display', read_only=True)
    order = serializers.SerializerMethodField(read_only=True)
    order_num = serializers.SerializerMethodField(read_only=True)
    order_lists = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfoGROUP
        fields = ['id', 'create_time', 'group_status', 'group_status_str', 'expired_time', 'group_order_num', 'order', 'order_lists',
                  'order_num']

    def get_order(self, obj):
        data = {}
        data['goods_id'] = ''
        data['goods_name'] = ''
        data['merchant_name'] = ''
        data['merchant_id'] = ''
        data['level_name'] = ''
        data['order_id'] = ''
        data['id'] = ''
        data['price'] = ''
        data['group_price'] = ''
        try:
            order = OrderInfo.objects.get(id=obj.order_id)
            goods = obj.goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['merchant_name'] = goods.merchant.name
            data['merchant_id'] = goods.merchant_id
            if order.level:
                data['level_name'] = f'{order.level.name}(分店)'
            else:
                data['level_name'] = '总店'
            data['order_id'] = order.order_id
            data['id'] = order.id
            data['price'] = goods.price
            data['group_price'] = goods.group_price
        except:
            pass
        return data

    def get_order_lists(self, obj):
        data = []
        try:
            order_set = OrderInfo.objects.filter(group_id=obj.id)
            serializer_data = OrderInfoListModelSerializer(order_set, many=True).data
            for i in serializer_data:
                if str(i['id']) == obj.order_id:
                    i['group'] = '主'
                else:
                    i['group'] = '从'
                data.append(i)
        except:
            pass
        return data

    def get_order_num(self, obj):
        order_num =  OrderInfo.objects.filter(state__in=[2,3,15,8], group_id=obj.id).count()
        return order_num


class OrderSchengleListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    order_state_str = serializers.CharField(source='get_order_state_display', read_only=True)
    orderinfo = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderSchengle
        fields = ['id', 'orderinfo', 'orderId', 'formCode', 'create_time', 'order_state', 'order_state_str', 'resultDesc']

    def get_orderinfo(self, obj):
        data = {}
        try:
            order = obj.order
            data['id'] = order.id
            data['order_id'] = order.order_id
            data['state'] = order.state
            data['state_str'] = order.get_state_display()
            goods = OrderGoods.objects.filter(order_id=order.id).first().goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['default_image'] = goods.default_image.url
            merchant = order.merchant
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['reserved_mobile'] = order.reserved_mobile
        except:
            pass
        return data


class OrderSchengleRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    coupons = serializers.SerializerMethodField(read_only=True)
    orderinfo = serializers.SerializerMethodField(read_only=True)
    order_state_str = serializers.CharField(source='get_order_state_display', read_only=True)

    class Meta:
        model = OrderSchengle
        fields = ['id', 'orderId', 'formCode', 'create_time', 'order_state', 'order_state_str', 'resultDesc',
                  'end_time', 'start_time', 'coupons', 'orderinfo']

    def get_coupons(self, obj):
        try:
            order = obj.order
            if order.order_type == 3:
                sd_order = obj
                if sd_order.order_state in [4, 2] and sd_order.end_time >= datetime.datetime.now():
                    result = schengle.query_order({"outTradeNo": sd_order.outTradeNo})
                    if result['resultCode'] == 'success':
                        couponInfoList = result['data']['couponDetailList']
                        use_time = None
                        for couponInfo in couponInfoList:
                            couponId = couponInfo['couponId']
                            if couponInfo['status'] == 5:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=5,
                                                                                              useTime=couponInfo['useTime'],
                                                                                              useShopCode=couponInfo['useShopCode'],
                                                                                              useShopName=couponInfo['useShopName'],
                                                                                              useCityCode=couponInfo['useCityCode'],
                                                                                              useCityName=couponInfo['useCityName'],
                                                                                              )
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(use_time=couponInfo['useTime'], status=2)
                                sd_order.order_state = 4
                                sd_order.save()
                            elif couponInfo['status'] == 6:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=6)
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(status=3)
                        check_coupons = OrderSchengleCoupons.objects.filter(order_id=order.id, coupon_state=1)
                        if not check_coupons:
                            sd_order.order_state = 5
                            sd_order.save()
                            order.state = 3
                            order.use_time = use_time
                            order.save()
        except:
            pass
        couponset = OrderSchengleCoupons.objects.filter(order_id=obj.order_id)
        return OrderSchengleCouponsModelSerializer(couponset, many=True).data

    def get_orderinfo(self, obj):
        data = {}
        try:
            order = obj.order
            data['id'] = order.id
            data['order_id'] = order.order_id
            data['state'] = order.state
            data['state_str'] = order.get_state_display()
            goods = OrderGoods.objects.filter(order_id=order.id).first().goods
            data['goods_id'] = goods.id
            data['goods_name'] = goods.name
            data['default_image'] = goods.default_image.url
            merchant = order.merchant
            data['merchant_id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['reserved_mobile'] = order.reserved_mobile
        except:
            pass
        return data


class OrderSchengleCouponsModelSerializer(serializers.ModelSerializer):

    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    startTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    endTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    useTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    service_name = serializers.SerializerMethodField(read_only=True)
    coupon_state_str = serializers.CharField(source='get_coupon_state_display', read_only=True)

    class Meta:
        model = OrderSchengleCoupons
        fields = ['id', 'couponId', 'useTime', 'createTime', 'startTime', 'endTime', 'coupon_state', 'coupon_state_str',
                  'useShopCode', 'useShopName', 'useCityCode', 'useCityName', 'service_name']

    def get_service_name(self, obj):
        try:
            dict1 = {
                "5264": "全套精洗（全车型）",
                "5221": "臭氧杀菌（不含洗车）",
                "4080": "汽车桑拿-空调清洗",
                "5058": "抛光打蜡（全车型）",
                "5261": "内饰清洗（全车型）",
            }
            return dict1[obj.serviceId]
        except:
            return ''


class OrderAdvanceModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderAdvance
        fields = ('id', 'create_time', 'remark', 'status', 'status_str', 'user')

    def get_user(self, obj):
        data = {}
        data['user_role'] = ''
        data['user_name'] = ''
        try:
            if obj.user:
                data['user_role'] = obj.user.role.name
                data['user_name'] = obj.user.nickname
            elif obj.merchantuser:
                data['user_role'] = '商家'
                data['user_name'] = obj.merchantuser.mobile
            else:
                data['user_role'] = '消费者'
                if obj.customeruser:
                    data['user_name'] = obj.customeruser.username
                else:
                    data['user_name'] = obj.customeruservice.username
        except:
            pass
        return data


class YSHAreaCodeModelSerializer(serializers.ModelSerializer):

    level_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = YSHAreaCode
        fields = ('id', 'code', 'prov_name', 'city_name', 'district_name', 'level', 'level_str', 'name')

    def get_level_str(self, obj):
        try:
            if obj.level == 1:
                return '省'
            elif obj.level == 2:
                return '市'
            elif obj.level == 3:
                return '区'
            else:
                return ''
        except:
            return ''


class YSHContractModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = YSHContract
        fields = ('id', 'supplierCode', 'supplierName', 'contractCode', 'contractName', 'taxRate')


class ExpressListModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str')

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressRetrieveModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    order_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str', 'expressplan_set', 'order_set')

    def get_order_set(self, obj):
        try:
            order_id_list = obj.expressorderrelevance_set.all().values_list('order_id', flat=True)
            order_set = OrderInfo.objects.filter(id__in=list(order_id_list))
            return OrderInfoListModelSerializer(order_set, many=True).data
        except:
            return []

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressQuestListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_enter_str = serializers.CharField(source='get_is_enter_display', read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ExpressQuest
        fields = ('id', 'create_time', 'file', 'logs_file', 'is_enter_str', 'is_enter', 'line_number', 'success_number', 'error_number', 'user')

    def get_user(self, obj):
        try:
            if obj.user:
                return obj.user.nickname
            else:
                return f'商户({obj.merchantuser.mobile})'
        except:
            return ''


class ExpressTypeModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExpressType
        fields = ('id', 'express_type_name', 'logo')
